package com.springboot.practice.controller;

import com.springboot.practice.domain.User;
import com.springboot.practice.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

/**
 * @Author 小柯
 * @Date 2019/9/22  9:38
 **/
@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    /**
     *
     * 功能描述:查询所有的用户
     */
    @GetMapping
    public ModelAndView list(Model model){

        model.addAttribute("userList", userRepository.listUser());
        model.addAttribute("title", "用户管理");
        return new ModelAndView("users/list", "userModel", model);
    }

    /**
     * 查询单个
     * @param model
     * @return
     */
    @GetMapping("{id}")
    public ModelAndView view(@PathVariable("id") Long id, Model model){

        model.addAttribute("user", (User)userRepository.getUserById(id));
        model.addAttribute("title", "查看用户");
        return new ModelAndView("users/view", "userModel", model);
    }


    /**
     * 创建单个
     * @param model
     * @return
     *
     *
     *
     *
     *
     *
     *
     *
     *
     *
     */
    @GetMapping("form")
    public ModelAndView createForm(Model model){

        model.addAttribute("user",new User());
        model.addAttribute("title", "创建管理");
        return new ModelAndView("users/form", "userModel", model);
    }

    @PostMapping
    public  ModelAndView saveOrUpdate(User user){
         user = userRepository.saveOrUpdateUaser(user);

        return new ModelAndView("redirect:/users"); // users重定向到页面
    }

    @GetMapping("/delete/{id}")
    public ModelAndView delete(@PathVariable("id") Long id){
        userRepository.deleteUser(id);
        return new ModelAndView("redirect:/users"); // users重定向到页面


    }

    /**
     * 查询单个
     * @param model
     * @return
     */
    @GetMapping("/modify/{id}")
    public ModelAndView modify(@PathVariable("id") Long id, Model model){
        User user = userRepository.getUserById(id);

        model.addAttribute("user", user);
        model.addAttribute("title", "修改用户");
        return new ModelAndView("users/view", "userModel", model);
    }



}
